﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.Administration;
using System.DirectoryServices;

namespace HostAssistantCore
{
     public  class FtpUtil
    {

        /// <summary>
        /// iis6删除ftp站点
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public static bool DeleteQFtp(string ftpname)
        {
            bool flag = false;
            try{

                /*
                * 删除FTP 子站点
                */
                var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                if (ftpname != "")
                {
                    foreach (DirectoryEntry sitechild in siteEntry.Children)
                    {
                        if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                            continue;
                        string yftpname = sitechild.Properties["ServerComment"].Value.ToString();
                        if (yftpname.ToLower() == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp").ToLower())
                        {
                            try
                            {
                                DirectoryEntry root = sitechild.Children.Find("ROOT", "IIsFtpVirtualDir");
                                var ftpchild = root.Children.Find(ftpname, "IIsFtpVirtualDir");
                                if (ftpchild != null)
                                {
                                    //删除
                                    root.Children.Remove(ftpchild);
                                    root.CommitChanges();
                                    sitechild.CommitChanges();
                                    siteEntry.CommitChanges();
                                    flag = true;
                                }
                            }
                            catch
                            {
                                flag = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
            }
            return flag;
        }
        /// <summary>
        /// 删除ftp站点
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public static bool DeleteFtp(string ftpname)
        {
            bool flag = false;
            try
            {
                using (ServerManager iisManager = new ServerManager())
                {
                    Site site = iisManager.Sites.FirstOrDefault(o => ((string)o["name"]).Contains(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp")));
                    var vird = site.Applications[0].VirtualDirectories["/" + ftpname];
                    if (vird != null)
                    {
                        //删除
                        site.Applications[0].VirtualDirectories.Remove(vird);
                        iisManager.CommitChanges();
                        flag = true;
                    }
                }
            }
            catch (Exception ex )
            {
                NLogger.Error(ex.ToString());
            }
            return flag;
        }
        /// <summary>
        /// iis6获取所有ftp站点信息
        /// </summary>
        /// <param name="newsitename"></param>
        /// <returns></returns>
        public static List<string> iGetFtpInfos()
        {
            List<string> ftpinfos = new List<string>();
            try
            {
                string ftproot = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp");
                string ftpname = "";//用户名
                string ftppass = "";//密码
                string ftppath = "";//物理路径
                string iisversion = "";//iis版本
                string majorversion = IISInfoUtil.SGetIISMajorVersion();
                if (majorversion == "")
                {
                    iisversion = "未知";
                }
                else
                {
                    iisversion = majorversion.ToString();
                }
                /*
                 * 创建FTP 子站点
                 */
                var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                        continue;
                    string yftpname = sitechild.Properties["ServerComment"].Value.ToString();
                    string defaultftpname = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp");
                    if (yftpname == defaultftpname)
                    {
                        try
                        {
                            //获取站点信息
                            var root = sitechild.Children.Find("ROOT", "IIsFtpVirtualDir");
                            DirectoryEntries ftps = root.Children;
                            foreach (DirectoryEntry ftp in ftps)
                            {
                                ftpname = ftp.Name;
                                /*
                                 * 获取密码
                                 */
                                try
                                {
                                    /*
                                    * 循环站点获取站点信息
                                    */
                                    foreach (DirectoryEntry child in rootentry.Children)
                                    {
                                        if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value.ToString() == ftpname)
                                        {
                                            ftppass = child.Properties["AnonymousUserPass"].Value.ToString();
                                            /*
                                             * 获取站点目录
                                             */
                                            foreach (DirectoryEntry rootChild in child.Children)
                                            {
                                                string name = rootChild.Name.ToString();
                                                if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                                                {
                                                    if (rootChild.Properties["Path"].Value == null)
                                                    {
                                                        ftppath = "";
                                                    }
                                                    else
                                                    {
                                                        ftppath = rootChild.Properties["Path"].Value.ToString().Substring(0, rootChild.Properties["Path"].Value.ToString().LastIndexOf("\\"));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {

                                }
                                /*
                                 * 获取路径
                                 */
                                if(ftpname != "")
                                    ftpinfos.Add(ftproot + "-@-" + ftpname + "-@-" + ftppass + "-@-" + ftppath + "-@-" + iisversion);//添加到站点信息
                            }
                        }
                        catch
                        {

                        }
                    }
                }
            }
            catch
            {
            }
            return ftpinfos;//返回数据
        }
        /// <summary>
        /// 获取所有ftp站点信息
        /// </summary>
        /// <param name="newsitename"></param>
        /// <returns></returns>
        public static List<string> GetFtpInfos()
        {
            List<string> ftpinfos = new List<string>();
            try
            {
                string ftproot = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp");
                string ftpname = "";//用户名
                string ftppass = "";//密码
                string ftppath = "";//物理路径
                string iisversion = "";//iis版本
                string majorversion = IISInfoUtil.SGetIISMajorVersion();
                if (majorversion == "")  
                {
                    iisversion = "未知";
                }
                else
                {
                    iisversion = majorversion.ToString();
                }
                using (ServerManager iisManager = new ServerManager())
                {
                    try
                    {
                        Site site = iisManager.Sites.FirstOrDefault(o => ((string)o["name"]).Contains(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp")));
                        VirtualDirectoryCollection ftps = site.Applications[0].VirtualDirectories;
                        foreach (VirtualDirectory ftp in ftps)
                        { 
                            //permissions
                           // NLogger.Fatal("permissions:"+ ftp.GetAttributeValue("permissions").ToString());  
                             ftpname = ftp.Path.Substring(1);
                            ftppass = GetPassword(ftpname);
                            ftppath = ftp.PhysicalPath;
                            if(ftpname != "")
                                ftpinfos.Add(ftproot + "-@-" + ftpname + "-@-" + ftppass + "-@-" + ftppath + "-@-" + iisversion);//添加到站点信息
                        }
                    }
                    catch (Exception ex)
                    {
                        NLogger.Error(ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
            }
            return ftpinfos;//返回信息
        }
        /// <summary>
        /// 创建默认的FTP站点
        /// </summary>
        public int createFtpSite(string ftpname,string path){

            int errorCode = ErrorCode.Succeed;
            if (ftpname == "" && path == "")
            {
                try
                {
                    ServerManager iisManager = new ServerManager();
                    Configuration cfg = iisManager.GetApplicationHostConfiguration();
                    /*---- 停止21端口 ----*/
                    try
                    {
                        /*---- sites ----*/
                        foreach (var ftpsite in iisManager.Sites)
                        {
                            /*
                            * 站点描述
                            */
                            string sitename = ftpsite.Name;
                            /*
                            * 站点绑定域名和端口
                            */
                            foreach (Binding binding in ftpsite.Bindings)
                            {
                                try
                                {
                                    string currentServerBindings = binding.GetAttributeValue("BindingInformation").ToString();
                                    string port = currentServerBindings.Split(":".ToArray())[1];
                                    if (port == "21")
                                    {
                                        try
                                        {
                                            //stop site
                                            ftpsite.Stop();
                                        }
                                        catch
                                        {
                                            //doing nothing
                                        }
                                        break;
                                    }
                                }
                                catch
                                {
                                    //doing nothing
                                }
                            }
                        }
                        //提交更改
                        iisManager.CommitChanges();
                    }
                    catch
                    {
                        //do nothing
                    }
                    /*
                     * 创建FTP
                    */
                    if (!System.IO.Directory.Exists(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath")))//创建站点路径
                    {
                        System.IO.Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath"));
                    }
                    Site site = iisManager.Sites.Add(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"), "ftp", string.Format("*:{0}:", "21"), System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath"));
                    iisManager.CommitChanges();
                    //设置FTP SSL权限
                    SetFtpSSL();
                    //设置FTP Everyone权限
                    AddSiteUtil addsiteUtil = new AddSiteUtil();
                    try
                    {
                        string config_rootpath = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        //string rootpath = path.Substring(0, path.IndexOf(ftpname) - 1) + "\\ftproot";
                        if (!System.IO.Directory.Exists(config_rootpath))
                        {
                            System.IO.Directory.CreateDirectory(config_rootpath);
                        }
                        addsiteUtil.icaclsSet("Everyone", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath"));
                        /*---- hide ----*/
                        System.IO.File.SetAttributes(config_rootpath, System.IO.FileAttributes.Hidden);
                    }
                    catch
                    {

                    }
                }
                catch
                {
                    errorCode = ErrorCode.ftpSiteFail;
                }
                
            }
            else
            {
                if (!getFtpState(ftpname))//判断ftp用户是否存在
                {
                    /*---- FTP状态检查 ----*/
                    FtpStateInit();
                    try
                    {
                        using (ServerManager iisManager = new ServerManager())
                        {
                            Site site = iisManager.Sites.FirstOrDefault(o => ((string)o["name"]).Contains(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp")));
                            var vird = site.Applications[0].VirtualDirectories["/" + ftpname];
                            if (vird == null) { site.Applications[0].VirtualDirectories.Add("/" + ftpname, path); }
                            else { errorCode = ErrorCode.ftpExists; }
                            iisManager.CommitChanges();
                            //添加FTP访问权限
                            SetFtpAccess(ftpname);
                        }
                    }
                    catch
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                else
                {
                    errorCode = ErrorCode.ftpExists;
                }

            }
            return errorCode;
        }
        /// <summary>
        /// 检查ftp启动状态并更新
        /// </summary>
        public void FtpStateInit()
        {
            /*---- 停止21端口 ----*/
            try
            {
                if (!FtpState())
                {
                    ServerManager iisManager = new ServerManager();
                    Configuration cfg = iisManager.GetApplicationHostConfiguration();
                    /*---- sites ----*/
                    foreach (var ftpsite in iisManager.Sites)
                    {
                        /*
                        * 站点描述
                        */
                        string sitename = ftpsite.Name;
                        /*
                        * 站点绑定域名和端口
                        */
                        foreach (Binding binding in ftpsite.Bindings)
                        {
                            string currentServerBindings = binding.GetAttributeValue("BindingInformation").ToString();
                            string port = currentServerBindings.Split(":".ToArray())[1];
                            if (port == "21" && sitename != System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                            {
                                try
                                {
                                    //stop site
                                    ftpsite.Stop();
                                }
                                catch
                                {
                                    //doing nothing
                                }
                                break;
                            }
                        }
                    }
                    /*---- start ftp ---*/
                    FtpState();
                    //提交更改
                    iisManager.CommitChanges();
                } 
            }
            catch
            {
                //do nothing
            }
        }
        public bool FtpState()
        {
            /*---- 检查FTP状态 ----*/
            try
            {
                ServerManager iisManager = new ServerManager();
                Configuration cfg = iisManager.GetApplicationHostConfiguration();
                /*---- sites ----*/
                foreach (var ftpsite in iisManager.Sites)
                {
                    /*
                    * 站点描述
                    */
                    string sitename = ftpsite.Name;
                    /*
                     * FTP状态
                     */
                    if (sitename == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                    {
                        try
                        {
                            return true;
                            //if (ftpsite.State == ObjectState.Started)
                            //{
                            //    return true;
                            //}
                            //else
                            //{
                            //    ftpsite.Start();
                            //    return true;
                            //}
                        }
                        catch
                        {
                            return false;
                        }
                    }
                }
                //提交更改
                iisManager.CommitChanges();
            }
            catch
            {
                //do nothing
            }
            return true;
        }
        /// <summary>
        /// IIS6创建默认的FTP站点
        /// </summary>
        public int icreateFtpSite(string ftpname, string path)
        {

            int errorCode = ErrorCode.Succeed;
            if (ftpname == "" && path == "")
            {
                try
                {
                    /*--- 停止21端口 -----*/
                    try
                    {
                        var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                        foreach (DirectoryEntry sitechild in siteEntry.Children)
                        {
                            if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                                continue;
                            string sitename = sitechild.Properties["ServerComment"].Value.ToString();
                            /*--- try ----*/
                            try
                            {
                                sitechild.Invoke("Stop", new object[] { });//启动站点
                            }
                            catch
                            {
                                //do nothing
                            }
                        }
                    }
                    catch
                    {

                    }
                    /*
                     * 赋予FTP路径权限
                    */
                    if (!System.IO.Directory.Exists(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath")))//创建站点路径
                    {
                        System.IO.Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath"));
                    }
                    //设置FTP Everyone权限
                    AddSiteUtil addsiteUtil = new AddSiteUtil();
                    try
                    {
                        string config_rootpath = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        //string rootpath = path.Substring(0, path.IndexOf(ftpname) - 1) + "\\ftproot";
                        if (!System.IO.Directory.Exists(config_rootpath))
                        {
                            System.IO.Directory.CreateDirectory(config_rootpath);
                        }
                        addsiteUtil.icaclsSet("Everyone", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath"));
                        /*---- hide ----*/
                        System.IO.File.SetAttributes(config_rootpath, System.IO.FileAttributes.Hidden);
                    }
                    catch
                    {

                    }
                }
                catch
                {
                    errorCode = ErrorCode.ftpSiteFail;
                }
            }
            else
            {
                if (!igetFtpState(ftpname))//判断ftp用户是否存在
                {
                    try
                    {
                        /*---- ftp state init ----*/
                        FtpStateInit_Q();
                        /*
                         * 创建FTP 子站点
                         */
                        var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                        foreach (DirectoryEntry sitechild in siteEntry.Children)
                        {
                            if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                                continue;
                            string yftpname = sitechild.Properties["ServerComment"].Value.ToString();
                            string defaultftpname = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp");
                            if (yftpname == defaultftpname)
                            {
                                //建FTP
                                var ftproot = sitechild.Children.Find("ROOT", "IIsFtpVirtualDir");
                                var ftpchild = ftproot.Children.Add(ftpname, "IIsFtpVirtualDir");
                                ftpchild.Properties["AccessFlags"].Value = 3;
                                ftpchild.Properties["Path"].Value = path;
                                ftpchild.CommitChanges();
                                siteEntry.CommitChanges();
                                try
                                {
                                    ftpchild.Invoke("Start", new object[] { });
                                }
                                catch
                                {

                                }
                            }
                        }
                    }
                    catch
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                else
                {
                    errorCode = ErrorCode.ftpExists;
                }

            }
            return errorCode;
        }
        /// <summary>
        /// 检查ftp启动状态并更新
        /// </summary>
        public void FtpStateInit_Q()
        {
            /*--- 停止21端口 -----*/
            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                        continue;
                    string sitename = sitechild.Properties["ServerComment"].Value.ToString();
                    if (sitename != System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                    {
                        /*--- try ----*/
                        try
                        {
                            sitechild.Invoke("Stop", new object[] { });//启动站点
                        }
                        catch
                        {
                            //do nothing
                        }
                    }
                }
                /*---- 启动ftp ----*/
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                        continue;
                    string sitename = sitechild.Properties["ServerComment"].Value.ToString();
                    if (sitename == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                    {
                        /*--- try ----*/
                        try
                        {
                            sitechild.Invoke("Start", new object[] { });//启动站点
                        }
                        catch
                        {
                            //do nothing
                        }
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 查看FTP站点状态
        /// </summary>
        public bool getFtpState(string ftpname){

            bool flag = false;
            try
            {
                if (ftpname == "")
                {
                    using (ServerManager iisManager = new ServerManager())
                    {
                        Site site = iisManager.Sites.FirstOrDefault(o => ((string)o["name"]).Contains(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp")));
                        if (site != null) { flag = true; }
                    }
                }
                else
                {
                    using (ServerManager iisManager = new ServerManager())
                    {
                        Site site = iisManager.Sites.FirstOrDefault(o => ((string)o["name"]).Contains(System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp")));
                        var vird = site.Applications[0].VirtualDirectories["/" + ftpname];
                        if (vird != null)
                        {
                            flag = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());

            }
            return flag;
        }
        /// <summary>
        /// 查看FTP站点状态
        /// </summary>
        public bool igetFtpState(string ftpname)
        {
            bool flag = false;
            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                if (ftpname == "")
                {
                    foreach (DirectoryEntry sitechild in siteEntry.Children)
                    {
                        if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                            continue;
                        string yftpname = sitechild.Properties["ServerComment"].Value.ToString();
                        string defaultftpname = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp");
                        if (yftpname == defaultftpname)
                        {
                            flag = true;
                        }
                    }
                }
                else
                {

                    foreach (DirectoryEntry sitechild in siteEntry.Children)
                    {
                        if (!sitechild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                            continue;
                        string yftpname = sitechild.Properties["ServerComment"].Value.ToString();
                        if (yftpname.ToLower() == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp").ToLower())
                        {
                            try
                            {
                                var ftpchild = sitechild.Children.Find("ROOT", "IIsFtpVirtualDir").Children.Find(ftpname, "IIsFtpVirtualDir");
                                if (ftpchild != null)
                                {
                                    flag = true;
                                }
                            }
                            catch
                            {
                                flag = false;
                            }
                        }
                    }

                }
            }
            catch
            {

            }
            return flag;
        }
        /// <summary>
        /// IIS6创建用户ftp
        /// </summary>
        public int icreateFtpPoint(string ftpname, string path, int ftpId)
        {
            int errorCode = ErrorCode.Succeed;

            if (igetFtpState("") == false)//判断站点是否存在
            {
                try
                {
                    try
                    {
                        string config_rootpath = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        string rootpath = path.Substring(0, path.IndexOf(ftpname) - 1) + "\\ftproot";
                        if (rootpath != config_rootpath)
                        {
                            System.Configuration.ConfigurationManager.AppSettings.Set("defaultftpath", rootpath);
                        }
                        if (!System.IO.Directory.Exists(rootpath))
                        {
                            System.IO.Directory.CreateDirectory(rootpath);
                        }
                    }
                    catch
                    {

                    }
                    /*
                     * 设置FTP权限
                     */
                    icreateFtpSite("", "");
                    /*
                     * 创建FTP ROOT站点
                     */
                    var siteEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象
                    //建FTP
                    var ftp = siteEntry.Children.Add(ftpId.ToString(), "IIsFtpServer");
                    ftp.Properties["ServerAutoStart"].Value = true;
                    ftp.Properties["AccessFlags"].Value = 1;
                    ftp.Properties["AllowAnonymous"].Value = true;
                    ftp.Properties["BannerMessage"].Value = "Welcome!";
                    ftp.Properties["ExitMessage"].Value = "Goodbye...";
                    ftp.Properties["GreetingMessage"].Value = "您已连接本站FTP服务器";
                    ftp.Properties["MSDOSDirOutput"].Value = false;
                    ftp.Properties["MaxClientsMessage"].Value = "超过最大连接了";
                    ftp.Properties["MaxConnections"].Value = "100000";
                    ftp.Properties["ServerAutoStart"].Value = true;
                    ftp.Properties["ServerBindings"].Value = ":21:";
                    ftp.Properties["ServerComment"].Value = "FTP";
                    //建ROOT根目录
                    var ftproot = ftp.Children.Add("ROOT", "IIsFtpVirtualDir");
                    ftproot.Properties["Path"].Value = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                    ftproot.Properties["DontLog"].Value = false;
                    ftproot.Properties["AccessFlags"].Value = 1;   
                    ftp.CommitChanges();
                    ftproot.CommitChanges();
                    siteEntry.CommitChanges();
                    ftp.Invoke("Start", new object[] { });
                    /*
                    * 创建用户ftp
                    */
                    if (icreateFtpSite(ftpname, path) != ErrorCode.Succeed)
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                catch
                {
                    errorCode = ErrorCode.ftpSiteFail;
                }
            }
            else
            {
                /*---- ftp root path ----*/
                try
                {
                    string rootpath = "";
                    if (System.IO.Directory.Exists(@"D:\"))
                    {
                        string ftproot = @"D:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (System.IO.Directory.Exists(@"E:\"))
                    {
                        string ftproot = @"E:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (System.IO.Directory.Exists(@"C:\"))
                    {
                        string ftproot = @"C:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (rootpath == "")
                    {
                        string config_path = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        AddSiteUtil addsiteUtil = new AddSiteUtil();
                        if (!System.IO.Directory.Exists(config_path))
                        {
                            System.IO.Directory.CreateDirectory(config_path);
                        }
                        addsiteUtil.icaclsSet("Everyone", config_path);
                        /*---- hide file ----*/
                        System.IO.File.SetAttributes(config_path, System.IO.FileAttributes.Hidden);
                    }
                }
                catch
                {

                }
                /*
                 * 直接创建FTP
                 */
                errorCode = icreateFtpSite(ftpname, path);
                if (errorCode == ErrorCode.ftpSiteFail)
                {
                    errorCode = ErrorCode.ftpSiteFail;
                }
                else if (errorCode == ErrorCode.ftpExists)
                {
                    errorCode = ErrorCode.ftpExists;
                }
            }
            return errorCode;
        }
        /// <summary>
        /// 创建用户ftp
        /// </summary>
        public int createFtpPoint(string ftpname,string path){

            int errorCode = ErrorCode.Succeed;
           
            if (getFtpState("") == false)//判断站点是否存在
            {
                /*
                 * 创建FTP ROOT站点
                 */
                try
                {
                    try
                    {
                        string config_rootpath = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        string rootpath = path.Substring(0, path.IndexOf(ftpname) - 1) + "\\ftproot";
                        if (rootpath != config_rootpath)
                        {
                            System.Configuration.ConfigurationManager.AppSettings.Set("defaultftpath", rootpath);
                        }
                        if (!System.IO.Directory.Exists(rootpath))
                        {
                            System.IO.Directory.CreateDirectory(rootpath);
                        }
                    }
                    catch (Exception ex)
                    {
                        NLogger.Error(ex.ToString());

                    }
                    errorCode = createFtpSite("", "");
                    if (errorCode == ErrorCode.Succeed)
                    {
                        ServerManager iisManager = new ServerManager();
                        Configuration cfg = iisManager.GetApplicationHostConfiguration();

                        ConfigurationSection ftpsection = cfg.GetSection("system.ftpServer/security/authorization", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"));
                        var ftpcollection = ftpsection.GetCollection();
                        /*
                        * 创建FTP访问权限
                        */
                        ConfigurationElement ftpserver = ftpcollection.CreateElement();
                        ftpserver.SetAttributeValue("accessType", "Allow");
                        ftpserver.SetAttributeValue("users", "*");
                        ftpserver.SetAttributeValue("permissions", "Read");
                        ftpcollection.Add(ftpserver);

                        /*
                         * 设置FTP默认应用池
                         */
                        ConfigurationSection sitesection = cfg.GetSection("system.applicationHost/sites");
                        var sitecollection = sitesection.GetCollection();
                        foreach (var siteinfo in sitecollection)
                        {
                            if (siteinfo.GetAttributeValue("name").ToString() == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                            {
                                siteinfo.GetCollection()[0].SetAttributeValue("applicationPool","DefaultAppPool");
                            }
                        }
                        //提交更改
                        iisManager.CommitChanges();
                         
                        /*
                         * 创建用户ftp
                         */
                        if (createFtpSite(ftpname, path) != ErrorCode.Succeed)
                        {
                            errorCode = ErrorCode.Unknown;
                        }
                    }
                    else
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                catch (Exception ex)
                {
                    NLogger.Error(ex.ToString());
                    errorCode = ErrorCode.ftpSiteFail;
                }

            }
            else
            {
                /*---- ftp root path ----*/
                try
                {
                    string rootpath = "";
                    if (System.IO.Directory.Exists(@"D:\"))
                    {
                        string ftproot = @"D:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (System.IO.Directory.Exists(@"E:\"))
                    {
                        string ftproot = @"E:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (System.IO.Directory.Exists(@"C:\"))
                    {
                        string ftproot = @"C:\html\ftproot";
                        if (System.IO.Directory.Exists(ftproot))
                        {
                            rootpath = ftproot;
                        }
                    }
                    if (rootpath == "")
                    {
                        string config_path = System.Configuration.ConfigurationManager.AppSettings.Get("defaultftpath");
                        AddSiteUtil addsiteUtil = new AddSiteUtil();
                        if (!System.IO.Directory.Exists(config_path))
                        {
                            System.IO.Directory.CreateDirectory(config_path);
                        }
                        addsiteUtil.icaclsSet("Everyone", config_path);
                        /*---- hide file ----*/
                        System.IO.File.SetAttributes(config_path, System.IO.FileAttributes.Hidden);
                    }
                }
                catch (Exception ex)
                {
                    NLogger.Error(ex.ToString());

                }
                /*
                 * 直接创建FTP
                 */
                errorCode = createFtpSite(ftpname, path);
                if (errorCode == ErrorCode.ftpSiteFail)
                {
                    errorCode = ErrorCode.ftpSiteFail;
                }
                else if (errorCode == ErrorCode.ftpExists)
                {
                    errorCode = ErrorCode.ftpExists;
                }
            }
            return errorCode;
        }
        /*
         * 修改FTP密码
         */
        public static bool PasswordChange(string account, string password)
        {
            /*
             * 修改本地用户密码
             */
            ADUser.PwdModify(account, password);
            using (ServerManager iisManager = new ServerManager())
            {
                /*
                 * 修改应用池密码
                 */
                Site website = iisManager.Sites[account];
                if (website == null) { return false; };
                VirtualDirectory webvirdir = website.Applications[0].VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                webvirdir.Password = password;
                iisManager.CommitChanges();
            }
            return true;
        }
        /*
         * 获取FTP密码
         */
        public static string GetPassword(string account)
        {
            string getpassword = "";
            using (ServerManager iisManager = new ServerManager())
            {
                try
                {
                    /*
                     * 获取应用池
                     */
                    Site website = iisManager.Sites[account];
                    VirtualDirectory webvirdir = website.Applications[0].VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    getpassword = webvirdir.Password;
                    iisManager.CommitChanges();
                }
                catch (Exception ex)
                {
                    NLogger.Error(ex.ToString());
                }
            }
            return getpassword;
        }
        /*
        * 获取FTP密码
        */
        public static string GetSiteUser(string account)
        {
            string username = "";
            using (ServerManager iisManager = new ServerManager())
            {
                try
                {
                    /*
                     * 获取应用池
                     */
                    Site website = iisManager.Sites[account];
                    VirtualDirectory webvirdir = website.Applications[0].VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    username = webvirdir.UserName;
                    iisManager.CommitChanges();
                }
                catch
                {

                }
            }
            return username;
        }
        /// <summary>
        /// 设置FTP SSL权限以及FTP访问问候
        /// </summary>
        private static void SetFtpSSL(){

            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
                ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();


                foreach (ConfigurationElement siteinfo in sitesCollection)
                {
                    if (siteinfo.GetAttributeValue("name").ToString() == System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp"))
                    {
                        ConfigurationElement ftpServerElement = siteinfo.GetChildElement("ftpServer");
                        ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");

                        //SSL权限
                        ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
                        sslElement["controlChannelPolicy"] = @"SslAllow";
                        sslElement["dataChannelPolicy"] = @"SslAllow";
                        ConfigurationElement authElement = securityElement.GetChildElement("authentication");
                        ConfigurationElement basicAuthentication = authElement.GetChildElement("basicAuthentication");
                        basicAuthentication["enabled"] = true;
                        //访问问候
                        ConfigurationElement message = ftpServerElement.GetChildElement("messages");
                        message["exitMessage"] = "Goodbye...";
                        message["greetingMessage"] = "您已连接本站FTP服务器";
                        message["bannerMessage"] = "Welcome!";
                        message["maxClientsMessage"] = "超过最大连接了";
                        ConfigurationElement userIsolation = ftpServerElement.GetChildElement("userIsolation");
                        userIsolation["mode"] = "StartInUsersDirectory";
                        ConfigurationElement directoryBrowse = ftpServerElement.GetChildElement("directoryBrowse");
                        directoryBrowse["showFlags"] = "StyleUnix";

                        serverManager.CommitChanges();
                    }
                }
            }
        }
        /// <summary>
        /// 设置FTP访问权限
        /// </summary>
        /// <param name="ftpname"></param>
        private void SetFtpAccess(string ftpname)
        {

            NLogger.Info("设置FTP访问权限");

            /*----in----*/
            try
            {
                ServerManager iisManager = new ServerManager();
                Configuration cfg = iisManager.GetApplicationHostConfiguration();
                ConfigurationSection ftpsection = cfg.GetSection("system.ftpServer/security/authorization", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp") + "/" + ftpname);
                var ftpcollection = ftpsection.GetCollection();
                /*
                * 创建FTP访问权限
                */
                ConfigurationElement ftpserver = ftpcollection.CreateElement();
                ftpserver.SetAttributeValue("accessType", "Allow");
                ftpserver.SetAttributeValue("users", ftpname);
                ftpserver.SetAttributeValue("permissions", "Read, Write");
                ftpcollection.Add(ftpserver);

                /*
                * 设置FTP未知属性
                */
                ConfigurationSection ipsecurity = cfg.GetSection("system.ftpServer/security/ipSecurity", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp") + "/" + ftpname);
                ipsecurity["allowUnlisted"] = true;

                //提交更改
                iisManager.CommitChanges();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                //doing nothing
            }
        }



        public void SetFtpAccessnew(string ftpname,bool rw)
        {
            /*----in----*/
            try
            { 
                ServerManager iisManager = new ServerManager();
                Configuration cfg = iisManager.GetApplicationHostConfiguration();
                ConfigurationSection ftpsection = cfg.GetSection("system.ftpServer/security/authorization", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp") + "/" + ftpname);

                

                var ftpcollection = ftpsection.GetCollection();
                ftpcollection.Clear();
                //ftpcollection.co
                // ftpsection.RevertToParent();
                // ConfigurationElement ftpserver = ftpcollection.Remove();
                //  ConfigurationElement delftpserver = new ConfigurationElement.;
                // new ConfigurationElement()


                //  ftpcollection.Remove(ftpcollection.SetAttributeValue("users", ftpname));


                // ConfigurationElement ftpserver2 = ftpcollection.GetChildElement("permissions");


                //ftpserver2.SetAttributeValue("accessType", "Allow");
                //ftpserver2.SetAttributeValue("users", ftpname);

                //ftpserver2.SetAttributeValue("permissions", "Read, Write");

                //ftpserver2.SetAttributeValue("permissions", "Read");





                //ftpcollection.Remove (ftpserver2);

                //   ftpsection.SetAttributeValue("permissions", "Read");
                //////if (rw)
                //////    ss.Value = "Read, Write";
                //////else
                //////    ss.Value = "Read";
                ///////*
                //////* 创建FTP访问权限
                //////*/
                ConfigurationElement ftpserver = ftpcollection.CreateElement();


                ftpserver.SetAttributeValue("accessType", "Allow");
                ftpserver.SetAttributeValue("users", ftpname);
                if (rw)
                    ftpserver.SetAttributeValue("permissions", "Read, Write");
                else
                    ftpserver.SetAttributeValue("permissions", "Read");


                ftpcollection.Add(ftpserver);

                /*
                * 设置FTP未知属性
                */
                ConfigurationSection ipsecurity = cfg.GetSection("system.ftpServer/security/ipSecurity", System.Configuration.ConfigurationManager.AppSettings.Get("defaultftp") + "/" + ftpname);
                ipsecurity["allowUnlisted"] = true;

                //提交更改
                iisManager.CommitChanges();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                //doing nothing
            }
        }



    }
}
